package com.xinyan.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ValidateCode {
    private int width = 160;
    private int height = 40;
    private int codeCount = 4;
    // 干扰线
    private int lineCount = 100;
    private String code;
    // 验证码范围,去掉0(数字)和O(拼音)容易混淆的(小写的1和L也可以去掉,大写不用了)
    private char[] codeSequence = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G',
            'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z', '2', '3', '4',
            '5', '6', '7', '8', '9'};
    public Random random = new Random();

    public BufferedImage creatCode() {
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        bufferedImage = graphics.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        graphics.dispose();
        graphics = bufferedImage.createGraphics();
        graphics.fillRect(0, 0, width, height);
        Font font = new Font("微软雅黑", Font.PLAIN, height - 4);
        graphics.setFont(font);
        int x1, y1, x2, y2;
        for (int i = 0; i < lineCount; i++) {
            x1 = random.nextInt(width);
            y1 = random.nextInt(height);
            x2 = x1 + random.nextInt(width / 8);
            y2 = y1 + random.nextInt(height / 8);
            final Color c = getRandomColor();
            graphics.setColor(c);
            graphics.drawLine(x1, y1, x2, y2);
        }
        StringBuffer stringBuffer = new StringBuffer();
        int fontWidth = width / (codeCount + 2);
        for (int i = 0; i < codeCount; i++) {
            char c = codeSequence[random.nextInt(codeSequence.length)];
            stringBuffer.append(c);
            graphics.setColor(getRandomColor());
            graphics.drawString(String.valueOf(c), (i + 1) * fontWidth + random.nextInt(fontWidth / 2), height - 5);
            stringBuffer.append(c);
        }
        code = stringBuffer.toString();
        return bufferedImage;

    }

    private Color getRandomColor() {
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }
}

